package com.xwb.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xwb.entity.Instorage;
import com.xwb.entity.Order;
import com.xwb.entity.User;
import com.xwb.entity.Warehouse;
import com.xwb.mapper.UserMapper;
import com.xwb.service.UserService;
//import com.xwb.utils.ProductToken;
import com.xwb.utils.ProductToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ProductToken productToken;


@RequestMapping("/login")
//@ResponseBody
public String Login(@RequestParam("username") String username,@RequestParam("psd") String password, Model model) throws JsonProcessingException {

    //获取当前的用户
    Subject subject = SecurityUtils.getSubject();
    //封装用户的登录数据生产token
    UsernamePasswordToken token = new UsernamePasswordToken(username, password);

    try {
        subject.login(token);//执行登录方法，如果没有异常就说明OK了
        //登录时，在redis中有这个用户的token就重置时效，没有就把用户名和token放入redis
        Map<String, String> stringStringMap =productToken.productToken(username, new ObjectMapper().writeValueAsString(token));
        model.addAttribute("token", new ObjectMapper().writeValueAsString(token));
        //return new ObjectMapper().writeValueAsString(token);
        return "redirect:toLoginScussessPage";
    } catch (UnknownAccountException e) {//用户名不存在
        model.addAttribute("msg","用户名错误");
        return "loginPage";
        //return "用户名错误";
    }catch (IncorrectCredentialsException e){//密码不存在
        model.addAttribute("msg","密码错误");
        return "loginPage";
        //return "密码错误";
    }
}


    @RequestMapping("/register")
    //@ResponseBody
    public String register(@RequestParam("username") String username,@RequestParam("psd") String psd,@RequestParam("qpsd") String qpsd,@RequestParam("phone") String phone, Model model) {

        String register = userService.register(username, psd, qpsd, phone);
        //cs.loadResourceDefine();
        if (register.equals("注册成功")){
            model.addAttribute("msg", register);
            return "loginPage";
        }
        else {
            model.addAttribute("msg",register);
            return "registerPage";
        }
    }

    @RequestMapping("/MyLogout")
    public String logout(){
        //获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "loginPage";
    }

    @RequestMapping("/inOldStorage")
    public String InOldStorage(@RequestParam("productId") String productId,@RequestParam("number") String number,Model model){
        if(productId.equals("")){//判断是否为空
            model.addAttribute("msg","商品Id为空");
            return "inOldStoragePage";
        }
        //把String类型转化为Int类型
        int IntProductId = Integer.parseInt(productId);
        int IntNumber = Integer.parseInt(number);

        String username = ((User) SecurityUtils.getSubject().getPrincipal()).getUsername();
        //String username = ((org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        User user = userMapper.selectList(null).stream().filter(x -> x.getUsername().equals(username)).findAny().orElse(new User(0, new Date(), new Date(), "0", "0", "0", 0));
        //用登录用户的用户名找到用户ID

        //业务功能实现
        String s = userService.inOldStorage(IntProductId, IntNumber,user.getUserid());
        if(s.equals("此商品为新商品，请选择进新货")||s.equals("商品Id为空")){
            model.addAttribute("msg",s);
            return "inOldStoragePage";
        }
        else return "redirect:/userQueryWareHouse";
    }

    @RequestMapping("/inNewStorage")
    public String InNewStorage(@RequestParam("productid") String productid,@RequestParam("productname") String productname,@RequestParam("price") String price,@RequestParam("number") String number,@RequestParam("providerid") String providerid,Model model){
        if(productid.equals("")){//判断是否为空
            model.addAttribute("msg","商品Id为空");
            return "inNewStoragePage";
        }
        int IntProductId = Integer.parseInt(productid);
        int IntNumber = Integer.parseInt(number);
        int IntPrice = Integer.parseInt(price);
        int IntProviderid = Integer.parseInt(providerid);


        String username = ((User) SecurityUtils.getSubject().getPrincipal()).getUsername();
        //String username = ((org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername();
        User user = userMapper.selectList(null).stream().filter(x -> x.getUsername().equals(username)).findAny().orElse(new User(0, new Date(), new Date(), "0", "0", "0", 0));
        //用登录用户的用户名找到用户ID

        Instorage instorage = new Instorage(IntProductId, productname, IntPrice, new Date(), IntNumber, IntProviderid, user.getUserid());
        String s = userService.inNewStorage(instorage);
        if(s.equals("商品号已存在,请选择进货")||s.equals("此供应商不存在")){
            model.addAttribute("msg",s);
            return "inNewStoragePage";
        }
        else return "redirect:/userQueryWareHouse";
    }

    @RequestMapping("/outStorage")
    public String OutStorage(@RequestParam("productId") String productId,@RequestParam("number") String number,@RequestParam("retailerId") String retailerId,Model model){
        if(productId.equals("")){//判断是否为空
            model.addAttribute("msg","商品Id为空");
            return "outStoragePage";
        }
        int IntProductId = Integer.parseInt(productId);
        int IntNumber = Integer.parseInt(number);
        int IntRetailerId = Integer.parseInt(retailerId);

        String username = ((User) SecurityUtils.getSubject().getPrincipal()).getUsername();
        //这句话可以直接获取登录当前页面的用户名
        User user = userMapper.selectList(null).stream().filter(x -> x.getUsername().equals(username)).findAny().orElse(new User(0, new Date(), new Date(), "0", "0", "0", 0));
        //用登录用户的用户名找到用户ID

        String s = userService.outStorage(IntProductId, IntNumber, IntRetailerId , user.getUserid());
        if(s.equals("无此商品")||s.equals("库存商品数量不足")||s.equals("无此销售商")){
            model.addAttribute("msg",s);
            return "outStoragePage";
        }
        return "redirect:/userQueryWareHouse";
    }

    @RequestMapping("/userQueryWareHouse")
    @RequiresRoles("0")
    public String queryWareHouse(Model model){
        List<Warehouse> warehouses = userService.userQureyAllWarHouse();
        model.addAttribute("List",warehouses);
//        for (Warehouse warehouse : warehouses) {
//            warehouse.getProductid()
//        }
        return "userQueryWareHousePage";
    }

    @RequestMapping("/userQueryWareHouseBySort")
    @RequiresRoles("0")
    public String queryWareHouseBySort(){
        List<Warehouse> warehouses = userService.userQureyAllWarHouseBySort();
        return "userQueryWareHousePage";
    }

    @RequestMapping("/userQueryAllInstorage")
    @RequiresRoles("0")
    public String userQueryAllInstorage(Model model){
        List<Order> hashMaps = userService.userQueryAllInstorage();
        model.addAttribute("List",hashMaps);
        return "userQueryAllInstoragePage";
    }

    @RequestMapping("/userQueryAllOutstorage")
    public String userQueryAllOutstorage(Model model){
        List<Map<String, Object>> Maps = userService.userQueryAllOutstorage();
        model.addAttribute("List",Maps);
        return "userQueryAllOutstoragePage";
    }

}
